package com.tee.live.im.core.server.handler;

import com.tee.live.common.interfaces.topic.ImCoreServerProviderTopicNames;
import com.tee.live.im.core.server.common.ImContextUtils;
import com.tee.live.im.core.server.common.ImMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 业务消息处理器
 *
 * @author tee
 * @date 2025/10/22
 */
@Component
public class BizImMsgHandler implements SimplyHandler {

    @Resource
    private MQProducer mqProducer;

    private static Logger log = LoggerFactory.getLogger(BizImMsgHandler.class);

    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        // 参数校验
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null || appId == null) {
            log.error("attr error,imMsg is {}", imMsg);
            ctx.close();
            throw new IllegalArgumentException("attr is error");
        }
        byte[] body = imMsg.getBody();
        if (body == null || body.length == 0) {
            log.error("imMsg is {}", imMsg);
            ctx.close();
            throw new IllegalArgumentException("imMsg is");
        }
        Message message = new Message();
        message.setTopic(ImCoreServerProviderTopicNames.SY_LIVE_IM_ACK_MSG_TOPIC);
        message.setBody(body);


        try {
            SendResult sendResult = mqProducer.send(message);
            log.info("[BizImMsgHandler] 消息投递结果:{}", sendResult);
        } catch (Exception e) {
            log.error("send error,error is:{}",e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }
}
